package com.zhj.network.udp.chat;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * @PackageName:com.zhj.network.udp.chat
 * @ClassName:TalkSend
 * @auter: 朱慧杰
 * @date:2020/7/21 0021 14:04
 **/
public class TalkSend implements Runnable {

    DatagramSocket socket = null;
    BufferedReader reader = null;

    private int fromPort;
    private String toIp;
    private int toPort;

    public TalkSend(int fromProt, String toIp, int toPort) {
        this.fromPort = fromProt;
        this.toIp = toIp;
        this.toPort = toPort;

        try {
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {

        while (true) {
            try {
                String msg = reader.readLine();

                byte[] data = msg.getBytes();

                DatagramPacket packet = new DatagramPacket(data, 0, data.length, new InetSocketAddress(this.toIp,this.toPort));

                socket.send(packet);

                if (msg.equals("bye")) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
